//
//  EPCUserAccount.swift
//  Weibo
//
//  Created by LioWu on 09/04/2017.
//  Copyright © 2017 MyGit. All rights reserved.
//

import UIKit

private let userAccountFile:NSString = "userAccountPath.json"

class EPCUserAccount: NSObject {
    
    var access_token: String? //= "2.00zPhPGGF7jIME08a66a08afRBu4KB"
    
    var uid: String?
    
    var screen_name: String?
    
    var avatar_large: String?
    
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date.init(timeIntervalSinceNow: expires_in)
        }
    }
    
    var expiresDate: Date?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
    
        guard let filePath = userAccountFile.cz_appendDocumentDir(),
            let data = NSData.init(contentsOfFile: filePath),
            let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject] else {
                
            return
        }
        
        yy_modelSet(with: dict ?? [:] )
        
        // blow, test expires
        // expiresDate = Date.init(timeIntervalSinceNow: -3600*24)
        
        if expiresDate?.compare(Date()) != .orderedDescending {
            
            // 1.clear access_token/uid
            access_token = nil
            uid = nil
            
            // 2.remove userAccountFile.json
            _ = try? FileManager.default.removeItem(atPath: filePath)
        }
        
        debugPrint(dict ?? [:])
    }
    
    func saveAccount() {
        var dict = self.yy_modelToJSONObject() as? [String: AnyObject] ?? [:]
        
        dict.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
        let filePath = userAccountFile.cz_appendDocumentDir() else {
            
            return
        }
        
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("用户保存成功：\(filePath)")
    }
}
